package com.mtf.verifySign.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mtf.handler.exception.BusinessException;
import com.mtf.verifySign.entity.Key;
import com.mtf.verifySign.entity.TestSecretSaveParam;
import com.mtf.verifySign.mapper.KeyMapper;
import com.mtf.verifySign.service.IKeyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author matengfei
 * @Date 2024/6/13 15:06
 * @PackageName:com.mtf.verifySign.service.impl
 * @ClassName: KeyServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Slf4j
@Service
public class KeyServiceImpl extends ServiceImpl<KeyMapper, Key> implements IKeyService {

    @Override
    public void validateSign(TestSecretSaveParam param) {
        //appKey
        String appKey = param.getAppKey();  //test
        //参数中的sign
        String paramSign = param.getSign(); //78ec94f7846ea999ea29bc9bdc911f36
        //找这个appKey对应的秘钥
        String secret = getSecret(appKey);
        //计算sign
        String sign = getSign(param, secret);
        if(!paramSign.equals(sign)){
            throw new BusinessException("md5不匹配");
        }
    }

    private String getSign(TestSecretSaveParam param, String secret) {
        //先移除secret参数
        param.setSign(null);
        //序列化成字符串
        String jsonStr = JSON.toJSONString(param);
        //利用fastJson的反序列化，来进行排序
        JSONObject jsonObject = JSON.parseObject(jsonStr, Feature.OrderedField);
        //获取排序后的参数
        String sortedStr = jsonObject.toString();
        //加上秘钥
        String waitMd5 = sortedStr + secret;
        //md5加密
        String md5 = SecureUtil.md5(waitMd5);
        log.info("md5加密的内容：{}，期望匹配的md5: {}", waitMd5, md5);
        return md5;
    }

    private String getSecret(String appKey){
        LambdaQueryWrapper<Key> wr = new LambdaQueryWrapper<>();
        //只查询秘钥
        wr.select(Key::getSecret);
        //根据appKey匹配
        wr.eq(Key::getAppKey, appKey);
        List<Key> list = baseMapper.selectList(wr);
        if(CollectionUtil.isEmpty(list)){
            throw new BusinessException(String.format("appKey %s 不存在", appKey));
        }
        if(list.size() > 1){
            throw new BusinessException("1个appKey找到2条秘钥");
        }
        Key key = list.get(0);
        //秘钥
        return key.getSecret();
    }

}
